package com.netafull;

import java.net.URLEncoder;

import com.netafull.util.CloseUtil;
import com.netafull.util.GT_Http;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class NewsReply extends ShowAdActivity {

	ImageButton btn_back;
	ImageButton btn_send;
	EditText et_title;
	EditText et_content;
	String newsReplyName;// 评论名
	String newsReplyContent;// 评论内容

	int newsReplyId;
	//String newsReplyTitle;
	String path;
	String newsReplyUrl;// 发表评论url

	SharedPreferences sp;
	String getID;
	
	String result;
	
	ProgressDialog progress;
	
	boolean flag = false;
	
	boolean b = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsreply);
		
		show();
		
		CloseUtil.activityList.add(NewsReply.this);
		
		progress = new ProgressDialog(this);
		progress.setMessage(getResources().getString(R.string.tougao_wait));

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		newsReplyId = bundle.getInt("id");
		//newsReplyTitle = bundle.getString("title");
		//System.out.println("id="+newsReplyId+",title="+newsReplyTitle);
		path = getResources().getString(R.string.setcomment_url);

		et_title = (EditText) findViewById(R.id.et_title);
		et_content = (EditText) findViewById(R.id.et_content);
		
		et_content.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				newsReplyContent = et_content.getText().toString();
			}
		});
		
		btn_back = (ImageButton) findViewById(R.id.newsreply_button_left);
		btn_send = (ImageButton) findViewById(R.id.newsreply_button_right);
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (newsReplyContent==null || newsReplyContent.length()==0) {
					NewsReply.this.finish();
				} else {
					new AlertDialog.Builder(NewsReply.this)
						//.setTitle(R.string.prompt)
						.setMessage(R.string.determine_leave)
						.setPositiveButton(R.string.determine, new AlertDialog.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								NewsReply.this.finish();
							}
						}).setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						}).create().show();
				}
				//NewsReply.this.finish();
			}
		});
		btn_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean b1 = false;
				
				boolean b2 = false;
				
				// TODO Auto-generated method stub
				newsReplyName = et_title.getText().toString();
				if(newsReplyName.trim().length()==0){
					b1 = true;
				} else {
					b1 = false;
				}
				newsReplyName = URLEncoder.encode(newsReplyName);
				
				newsReplyContent = et_content.getText().toString();
				String temp = newsReplyContent.replaceAll("　"," ");
				if(temp.trim().length()==0){
					System.out.println("b2 = true");
					b2 = true;
				} else {
					System.out.println("b2 = false");
					b2 = false;
				}
				newsReplyContent = URLEncoder.encode(newsReplyContent);
				
				//newsReplyTitle = URLEncoder.encode(newsReplyTitle);
				System.out.println("newsReplyName="+newsReplyName+",newsReplyContent="+newsReplyContent);
				if (newsReplyName.equals("") || b1) {
					newsReplyUrl = path + "?id=" + newsReplyId + "&comment=" + newsReplyContent + "&device=Android";
				} else {
					newsReplyUrl = path + "?id=" + newsReplyId + "&nickname="
							+ newsReplyName + "&comment=" + newsReplyContent + "&device=Android";
				}
				System.out.println("newsReplyUrl=" + newsReplyUrl);
				if (!newsReplyContent.equals("")&&!b2) {
					sp = getSharedPreferences("netafull",
							Context.MODE_PRIVATE);
					getID = sp.getString("id_"+newsReplyId, "");
					//System.out.println(getID+","+newsReplyId);
					if (!getID.equals(newsReplyId+"")) {
						progress.show();
						Editor editor = sp.edit();
						editor.clear();
						editor.putString("id_"+newsReplyId, newsReplyId+"");
						editor.commit();
						sendMessage();
						
					} else {
						new AlertDialog.Builder(NewsReply.this)
								.setMessage(R.string.can_not_send_message)
								.setPositiveButton("OK",new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface arg0,
													int arg1) {
												// TODO Auto-generated method
												// stub

											}
										}).show();
					}
				} else {
					new AlertDialog.Builder(NewsReply.this)
							.setTitle(R.string.content_can_not_null_title)
							.setMessage(R.string.content_can_not_null_message)
							.setPositiveButton(
									getResources().getString(R.string.determine),
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {
											// TODO Auto-generated method stub

										}
									}).show();
				}
			}
		});
	}

	private void sendMessage() {
		// TODO Auto-generated method stub
		
		new Thread(){
			public void run() {
				System.out.println("开始发表");
				result = GT_Http.sendToServer(newsReplyUrl);
				if(analyzeResult(result)){
					//发表成功
					progress.dismiss();
					setResult(10);
					//Toast.makeText(NewsReply.this, R.string.send_success, Toast.LENGTH_SHORT).show();
					finish();
				} else {
					setResult(20);
					finish();
					//发表失败
					//Toast.makeText(NewsReply.this, R.string.send_failure, Toast.LENGTH_SHORT).show();
				}
				
			};
		}.start();
		
		
		/*Send send = new Send();
		send.op = this;
		send.start();*/
		//setResult(10);
		//finish();
	}
	private boolean analyzeResult(String result){
		
		/*
		 * 传入进来的参数类似于
		 * <?xml version="1.0" encoding="UTF-8"?>
		 * <result>
		 * 		<status>true</status>
		 * </result>
		 */
		if(result != null && result.endsWith("</result>")){
			String param[] = result.split("<status>");
			if(param[1].startsWith("true")){
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (newsReplyContent==null || newsReplyContent.length()==0) {
				NewsReply.this.finish();
			} else {
				new AlertDialog.Builder(this)
					.setMessage(R.string.determine_leave)
					.setPositiveButton(R.string.determine, new AlertDialog.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							NewsReply.this.finish();
						}
					}).setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					}).create().show();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			if(sp!=null){
				Editor editor = sp.edit();
				editor.clear();
				editor.commit();
			}
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		b = false;
		
	}

}
